package org.domeos.framework.api.controller.image;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.domeos.basemodel.HttpResponseTemp;
import org.domeos.basemodel.ResultStat;
import org.domeos.framework.api.biz.auth.AuthBiz;
import org.domeos.framework.api.biz.global.GlobalBiz;
import org.domeos.framework.api.biz.image.ImageBiz;
import org.domeos.framework.api.biz.project.ProjectBiz;
import org.domeos.framework.api.biz.project.ProjectCollectionBiz;
import org.domeos.framework.api.controller.common.BaseSreController;
import org.domeos.framework.api.model.auth.User;
import org.domeos.framework.api.model.ci.BuildHistory;
import org.domeos.framework.api.model.ci.related.CodeInfomation;
import org.domeos.framework.api.model.ci.related.ImageInformation;
import org.domeos.framework.api.model.global.Registry;
import org.domeos.framework.api.model.image.BaseImage;
import org.domeos.framework.api.model.image.related.ImageType;
import org.domeos.framework.api.model.project.Project;
import org.domeos.framework.api.model.project.ProjectCollection;
import org.domeos.framework.api.model.project.related.CustomDockerfile;
import org.domeos.framework.api.service.auth.UserService;
import org.domeos.framework.api.service.image.ImageService;
import org.domeos.framework.api.service.project.BuildService;
import org.domeos.framework.api.service.project.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 
 * @author lixiaokai
 *
 */

@Controller
@RequestMapping("/sre/api/image")
@Api("SRE部署相关API")
public class ImageSREController extends BaseSreController {
	
	@Autowired
    ImageService imageService;
	
	@Autowired
    UserService userService; 
	
	@Autowired
    ImageBiz imageBiz;
	
	@Autowired
	AuthBiz authBiz;
	
	@Autowired
    GlobalBiz globalBiz;
	
	@Autowired
	ProjectBiz projectBiz;
	
	@Autowired
	ProjectCollectionBiz projectCollectionBiz;
	
	@Autowired
    ProjectService projectService;

    @Autowired
    BuildService buildService;
	
	@ApiOperation(value="查看基础镜像是否存在")
    @ResponseBody
    @RequestMapping(value = "/base/isexist", method = RequestMethod.POST)
    public HttpResponseTemp<?> isBaseImageExist(@RequestBody BaseImage baseImage) {
		Registry registry = globalBiz.getRegistry();
		baseImage.setRegistry(registry.getUrl());
		BaseImage bi = imageBiz.getBaseImageByNameAndTag(baseImage.getImageName().toLowerCase(), baseImage.getImageTag(), baseImage.getRegistry());
        if (bi == null) {
            return ResultStat.BASE_IMAGE_ERROR.wrap("image not exist");
        }
        return ResultStat.OK.wrap(bi);
    }
	
	@ApiOperation(value="build基础镜像")
    @ResponseBody
    @RequestMapping(value = "/base/build", method = RequestMethod.POST)
    public HttpResponseTemp<?> build(@RequestParam("image_name") String imageName, @RequestParam("image_tag") String imageTag, @RequestParam("type") String imageType, @RequestParam("dockerfile") MultipartFile dockerfile, HttpServletRequest request) throws IOException {
		String userId = getUserId(request);
		if(StringUtils.isEmpty(userId)){
			return ResultStat.PARAM_ERROR.wrap("build userId is null!");
		}
		String dockerfileContent = new String(dockerfile.getBytes(), "UTF-8");
		if(StringUtils.isBlank(imageName) || StringUtils.isBlank(imageTag)) {
			return ResultStat.PARAM_ERROR.wrap("name and tag error");
		}
		if(!(imageType.equals(ImageType.BASE) || imageType.equals(ImageType.APPLICATION) || imageType.equals(ImageType.RELEASE))) {
			return ResultStat.PARAM_ERROR.wrap("type is not right");
		}
		imageName = imageName.toLowerCase();
        // 查询project collection
        ProjectCollection projectCollection = projectCollectionBiz.getProjectCollectionByName("sre");
        if(projectCollection == null) {
        	return ResultStat.PROJECT_COLLECTION_NOT_LEGAL.wrap("project_collecton_not_legal");
        }
        User user = userService.getUser(getIntValue(userId));
        if(user == null){
			return ResultStat.PARAM_ERROR.wrap("build userId is null!");
		}
        
        Project project = projectBiz.getProjectByName("sre/" + imageName);
        CustomDockerfile customDockerfile = new CustomDockerfile();
    	customDockerfile.setDockerfile(dockerfileContent);
    	
    	// 查询project是否存在
        if(project == null) {       	
        	//创建project
        	project = new Project();
        	project.setCustomDockerfile(customDockerfile);
        	project.setAuthority(0);
        	project.setName("sre/" + imageName);
        	HttpResponseTemp<?> createProjectStatus = projectService.sreCreateProject(user,projectCollection.getId(), project);
        	if(createProjectStatus.getResultCode() != 200) {
        		return createProjectStatus;
        	}
        }else {
        	// 更新project
        	project.setCustomDockerfile(customDockerfile);
        	HttpResponseTemp<?> updateProjectStatus = projectService.sreModifyProject(user,project);
        	if(updateProjectStatus.getResultCode() != 200) {
        		return updateProjectStatus;
        	}       	
        }
        
        // 检查base image是否已经存在
        BaseImage old = imageBiz.getBaseImageByNameAndTag("sre/" + imageName, imageTag, globalBiz.getRegistry().getUrl());
        if (old != null) {
            return ResultStat.BASE_IMAGE_ALREADY_EXIST.wrap("base image already exist");
        }
         
        ImageInformation imageInfo = new ImageInformation();
        CodeInfomation codeInfo = new CodeInfomation();
        BuildHistory buildInfo = new BuildHistory();
        imageInfo.setImageTag(imageTag);
        imageInfo.setImageType(imageType);
        buildInfo.setProjectId(project.getId());
        buildInfo.setImageInfo(imageInfo);
        buildInfo.setCodeInfo(codeInfo);
        
        return buildService.sreStartBuild(user,buildInfo);
    }
	
	@ApiOperation(value="查看镜像构建状态")
    @ResponseBody
    @RequestMapping(value = "/base/build/status/{id}", method = RequestMethod.GET)
    public HttpResponseTemp<?> buildStatusAndLog(@PathVariable int id) {
		BuildHistory buildHistory = projectBiz.getBuildHistoryById(id);
		return ResultStat.OK.wrap(buildHistory);
    }

}
